package com.djsblog.service.impl;

import java.sql.SQLException;
import java.util.List;

import com.djsblog.entity.Datadic;
import com.djsblog.entity.PageBean;
import com.djsblog.service.DataDicService;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.tx.Tx;
/**
 * 数据字典事务实现类
 * @author 但劲松
 *
 */
@Before(Tx.class)
public class DataDicServiceImpl implements DataDicService{

	public List<Datadic> find(Datadic s_datadic, PageBean pageBean) {
		StringBuffer sql = new StringBuffer("select * from datadic ");
		if(s_datadic!=null){
			if(StrKit.notBlank(s_datadic.getDel()))
				sql.append(" and del = '"+s_datadic.getDel()+"'");
			//模糊查询key
			if(StrKit.notBlank(s_datadic.getKey()))
				sql.append(" and `key` like '%"+s_datadic.getKey()+"%'");
			//模糊查询val
			if(StrKit.notBlank(s_datadic.getVal()))
				sql.append(" and `val` like '%"+s_datadic.getVal()+"%'");
		}
		//分页
		if(pageBean!=null) sql.append(" limit "+pageBean.getStart()+","+pageBean.getPageSize());
		return Datadic.dao.find(sql.toString().replaceFirst(" and", " where"));
	}
	public long count(Datadic s_datadic) {
		StringBuffer sql = new StringBuffer("select count(*) as total from datadic ");
		if(s_datadic!=null){
			if(StrKit.notBlank(s_datadic.getDel()))
				sql.append(" and del = '"+s_datadic.getDel()+"'");
			//模糊查询key
			if(StrKit.notBlank(s_datadic.getKey()))
				sql.append(" and `key` like '%"+s_datadic.getKey()+"%'");
			//模糊查询val
			if(StrKit.notBlank(s_datadic.getVal()))
				sql.append(" and `val` like '%"+s_datadic.getVal()+"%'");
		}
		return Db.queryLong(sql.toString().replaceFirst(" and", " where"));
	}

	public boolean save(Datadic datadic) {
		try{
			if(datadic.getId()==null){
				Datadic s_datadic = Datadic.dao.findFirst("select * from datadic where `key`='"+datadic.getKey()+"'");
				//key不存在
				if(s_datadic == null)
					return datadic.save();
				//key存在
				datadic.setId(s_datadic.getId());
				return datadic.update();
			}
			return datadic.update();
		}catch(Exception e){
			try {
				//执行失败回滚事务
				DbKit.getConfig().getConnection().rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			} 
		}
		return false;
	}

	public boolean deleteOrComeback(Long id, String del) {
		try{
			Datadic datadic = new Datadic();
			datadic.setId(id);
			datadic.setDel(del);
			return datadic.update();
		}catch(Exception e){
			try {
				//执行失败回滚事务
				DbKit.getConfig().getConnection().rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			} 
		}
		return false;
	}
	public Datadic getById(Long id) {
		return Datadic.dao.findById(id);
	}
	public String getByKey(String key) {
		return Db.queryStr("select val from datadic where `key`='"+key+"'");
	}
}
